package com.xiaok.netty.client.config;

import com.xiaok.common.util.BeanUtils;
import com.xiaok.netty.client.channelInitializer.ClientChannelInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * @Classname beansconfig
 * @Description 创建 bean 实例的配置类
 * @Date 2020/10/8 17:15
 * @Created by xiaok
 */
@Configuration
public class BeansConfig {

    @Value("${tcp.host}")
    private  String  tcpHost;
    @Value("${tcp.port}")
    private int tcpPort;

    /*根据名称装配，防止和客户端的ChannelInitializer冲突报错*/
    @Autowired
    @Qualifier("clientChannelInitializer")
    private ClientChannelInitializer clientChannelInitializer;

    /**
     * netty 客户端启动类
     * @return
     */
    @Bean(name="clientBootstrap")
    public Bootstrap bootstrap(){
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(clientLoopGroup())
                 .channel(NioSocketChannel.class)
                 .option(ChannelOption.SO_KEEPALIVE,true)
                .handler(clientChannelInitializer);

        return bootstrap;
    }

    /**
     * 事件循环组
     * @return
     */
    @Bean(name="clientLoopGroup")
    public NioEventLoopGroup clientLoopGroup(){return new NioEventLoopGroup();}

    /**
     * 定义 TCP 连接方式地址
     * @return
     */
    @Bean(name="tcpSocketAddress")
    public InetSocketAddress inetSocketAddress(){
        return new InetSocketAddress(tcpHost,tcpPort);
    }
    /*用于创建 bean 的工厂类*/
    @Bean
    @Lazy(value=false) //关闭懒加载
    public BeanUtils beanUtils(){
        return new BeanUtils();
    }
}
